//
//  AlbumXMLParser.m
//  Dolphin
//
//  Created by Matthew on 11-8-13.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "AlbumXMLParser.h"

@implementation AlbumXMLParser

@synthesize albumPathArr;
@synthesize albumTitleArr;
@synthesize albumIconArr;

@synthesize unit_width;
@synthesize unit_height;
@synthesize unit_between_width;
@synthesize unit_between_height;
@synthesize unit_start_off_x;
@synthesize unit_start_off_y;
@synthesize border_width;
@synthesize border_height;
@synthesize font_size;

-(void)startParsing:(NSString *) inXMLAddress
{
    dataReceiveErr = FALSE;
    
    if (inXMLAddress == Nil || [inXMLAddress length]<5) 
    {
        return;
    }
    
    NSString *fileNamePrefix = [inXMLAddress  substringWithRange:NSMakeRange(0, [inXMLAddress  length] - 4)];
    NSString *fileNameSuffix = [inXMLAddress substringWithRange:NSMakeRange([inXMLAddress length]-3,3)];
    
    NSString *path = [[NSBundle mainBundle] pathForResource:fileNamePrefix ofType:fileNameSuffix];
    NSData *xmlData = [NSData dataWithContentsOfFile:path];
    
    BOOL loadXmlFromWeb = FALSE;
    
    if([inXMLAddress length] > 11) 
    {
        NSString *httpSuffix = [inXMLAddress substringWithRange:NSMakeRange(0,7)];
        
        if([[httpSuffix lowercaseString] isEqualToString:@"http://"])
        {
            loadXmlFromWeb = YES;
            
            NSURL *url = [NSURL URLWithString:inXMLAddress];
            xmlDataBuffer = [[NSMutableData alloc] init];
            xmlLoadConnect = [[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self] retain];
            [xmlLoadConnect start];
        }
    }
    
    if (!loadXmlFromWeb)
    {
        xmlTextReaderPtr xmlreader = xmlReaderForMemory([xmlData bytes], 
                                                        [xmlData length], 
                                                        [path UTF8String], nil, 
                                                        (XML_PARSE_NOBLANKS | XML_PARSE_NOCDATA | XML_PARSE_NOERROR | XML_PARSE_NOWARNING));
        [self xmlParseProc:xmlreader];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    int statusCode = [((NSHTTPURLResponse *) response) statusCode];
    if (statusCode >= 400 && dataReceiveErr == FALSE)
    {
        UIAlertView *av= [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Web connection fail, please try later." delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
        [av show];
        dataReceiveErr = TRUE;
    }
    
    [xmlDataBuffer setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if (dataReceiveErr) 
    {
        return;
    }
    
    [xmlDataBuffer appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (dataReceiveErr)
    {
        return;
    }
    
    xmlTextReaderPtr xmlreader = xmlReaderForMemory([xmlDataBuffer  bytes], 
                                                    [xmlDataBuffer  length], 
                                                    nil, nil, 
                                                    (XML_PARSE_NOBLANKS | XML_PARSE_NOCDATA | XML_PARSE_NOERROR | XML_PARSE_NOWARNING));
    [self xmlParseProc:xmlreader];
    
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    dataReceiveErr = TRUE;
    UIAlertView *av= [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Web connection fail, please try later." delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
    [av show];
}

-(void) xmlParseProc:(xmlTextReaderPtr) xmlreader
{

    if (!xmlreader) 
    {
        NSLog(@"xmlreader load failure");
        return;
    }
    
    //init the data for read
    albumIconArr = [[NSMutableArray alloc] init];
    albumPathArr = [[NSMutableArray alloc] init];//array store the page's data.
    albumTitleArr = [[NSMutableArray alloc] init];
    
    NSString *tempTagName = Nil;
    NSString *tempTagValue = Nil; 
    NSString *currentTag = Nil;
    char *tempData;
    int count = 0;
    
    while (true) 
    {
        if (!xmlTextReaderRead(xmlreader))
        {    
            break;
        }
        
        //xml validate check
        count++; 
        if (count>100000) 
        {
            count = -1;
            break;
        }
        
        int curtype = xmlTextReaderNodeType(xmlreader);
        
        switch (curtype) 
        {
            case XML_READER_TYPE_ELEMENT:
                //We are starting an element
                tempData =  (char*)xmlTextReaderConstName(xmlreader);
                
                tempTagName = [NSString stringWithCString:tempData 
                                                 encoding:NSUTF8StringEncoding];
                               
                if([tempTagName isEqualToString:@"album"])//init the page set unit
                {                    
                    currentTag = @"album";
                }
                else if([tempTagName isEqualToString:@"global"])
                {
                    currentTag = @"global";
                }
                
                count++;
                continue;
            case XML_READER_TYPE_TEXT: 
                tempData = (char*)xmlTextReaderConstValue(xmlreader);
                tempTagValue = [NSString stringWithCString:tempData
                                                  encoding:NSUTF8StringEncoding];
                
                if ([currentTag isEqualToString:@"global"]) 
                {
                    if ([IPhone_IPad_Judge isIPad]) 
                    {
                        if ([tempTagName isEqualToString:@"unit_width"]) 
                        {
                            unit_width = [tempTagValue intValue];
                        }
                        else if ([tempTagName isEqualToString:@"unit_height"]) 
                        {
                            unit_height = [tempTagValue intValue];
                        }
                        else if ([tempTagName isEqualToString:@"unit_between_width"]) 
                        {
                            unit_between_width = [tempTagValue intValue];
                        }
                        else if ([tempTagName isEqualToString:@"unit_between_height"]) 
                        {
                            unit_between_height = [tempTagValue intValue];
                        }
                        else if ([tempTagName isEqualToString:@"unit_start_off_x"]) 
                        {
                            unit_start_off_x = [tempTagValue intValue];
                        }
                        else if ([tempTagName isEqualToString:@"unit_start_off_y"]) 
                        {
                            unit_start_off_y = [tempTagValue intValue];
                        }
                        else if([tempTagName isEqualToString:@"border_width"])
                        {
                            border_width = [tempTagValue intValue];
                        }
                        else if([tempTagName isEqualToString:@"border_height"])
                        {
                            border_height = [tempTagValue intValue];
                        }
                        else if([tempTagName isEqualToString:@"font_size"])
                        {
                            font_size = [tempTagValue intValue];
                        }
                    }
                    else
                    {
                        if ([tempTagName isEqualToString:@"unit_width_iphone"]) 
                        {
                            unit_width = [tempTagValue intValue];
                        }
                        else if ([tempTagName isEqualToString:@"unit_height_iphone"]) 
                        {
                            unit_height = [tempTagValue intValue];
                        }
                        else if ([tempTagName isEqualToString:@"unit_between_width_iphone"]) 
                        {
                            unit_between_width = [tempTagValue intValue];
                        }
                        else if ([tempTagName isEqualToString:@"unit_between_height_iphone"]) 
                        {
                            unit_between_height = [tempTagValue intValue];
                        }
                        else if ([tempTagName isEqualToString:@"unit_start_off_x_iphone"]) 
                        {
                            unit_start_off_x = [tempTagValue intValue];
                        }
                        else if ([tempTagName isEqualToString:@"unit_start_off_y_iphone"]) 
                        {
                            unit_start_off_y = [tempTagValue intValue];
                        }
                        else if([tempTagName isEqualToString:@"border_width_iphone"])
                        {
                            border_width = [tempTagValue intValue];
                        }
                        else if([tempTagName isEqualToString:@"border_height_iphone"])
                        {
                            border_height = [tempTagValue intValue];
                        }
                        else if([tempTagName isEqualToString:@"font_size_iphone"])
                        {
                            font_size = [tempTagValue intValue];
                        }
                    }

                }
                else if([currentTag isEqualToString:@"album"])
                {
                    if([tempTagName isEqualToString:@"album_icon" ])
                    {
                        [albumIconArr addObject:[[NSString alloc] initWithString:tempTagValue]];
                    }
                    else if ([tempTagName isEqualToString:@"album_path"]) 
                    {
                        [albumPathArr addObject:[[NSString alloc] initWithString:tempTagValue]];                                
                    }
                    else if ([tempTagName isEqualToString:@"album_name"]) 
                    {
                        [albumTitleArr addObject:[[NSString alloc] initWithString:tempTagValue]];   
                    }
                }
                
                tempTagValue = nil;
                tempTagName = nil;
                count++;
                continue;
                
            default: 
                continue;
        }
    }

    xmlreader = Nil;
    
    if(count == -1)
    {
        UIAlertView *av= [[[UIAlertView alloc] initWithTitle:@"Warning" message:@"Data load error. Please try later." delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:nil] autorelease];
        [av show];
    }
    else
    {        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"load_album_xml_over" object:self];
    }
    
}

-(void) reset
{
    if(xmlLoadConnect)
    {
        [xmlLoadConnect cancel];
        [xmlLoadConnect release];
    }
    
    if (xmlDataBuffer) 
    {
        [xmlDataBuffer setLength:0];
        [xmlDataBuffer release];
    }
    
    if (albumPathArr) 
    {
        [albumPathArr removeAllObjects];
        [albumPathArr release];
    }
    
    if (albumTitleArr) 
    {
        [albumTitleArr removeAllObjects];
        [albumTitleArr release];
    }
    
    if (albumIconArr) 
    {
        [albumIconArr removeAllObjects];
        [albumIconArr release];
    }
}

@end
